package com.yehun.annotation;

import com.yehun.config.MybatisDataSourceSwitch;
import com.yehun.utils.AnnotationUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


/**
 * 数据源切换
 * Created by Genius on 2017/5/3 0003.
 */
@Aspect
@Component("dataSourceAspect")
public class DataSourceAspect {

    private static final Logger logger = LoggerFactory.getLogger(DataSourceAspect.class);

    /**
     * 目标方法执行前
     */
    @Before("@annotation(com.yehun.annotation.DataSource)")
    public void beforeExec(JoinPoint point) {
        logger.info("DataSourceAspect -> beforeExec() ...");
        DataSource dataSource = AnnotationUtils.getAnnotation(point, DataSource.class);
        if (dataSource != null) {
            MybatisDataSourceSwitch.set(dataSource.type());
        }
    }

    /**
     * 目标方法执行后
     */
    @After("@annotation(com.yehun.annotation.DataSource)")
    public void afterExec(JoinPoint point) {
        logger.info("DataSourceAspect -> afterExec() ...");
        DataSource dataSource = AnnotationUtils.getAnnotation(point, DataSource.class);
        if (dataSource != null) {
            MybatisDataSourceSwitch.setDefault();
        }
    }

    /*
    @Around("@annotation(com.yehun.annotation.DataSource)")
    public Object aroundExec(ProceedingJoinPoint point) throws Throwable {
        logger.info("DataSourceAspect -> aroundExec() before...");
        DataSource dataSource = AnnotationUtils.getAnnotation(point, DataSource.class);
        if (dataSource != null) {
            MybatisDataSourceSwitch.set(dataSource.type());
            try {
                return point.proceed();
            } finally {
                MybatisDataSourceSwitch.setDefault();
            }
        }
        logger.info("DataSourceAspect -> aroundExec() after...");
        return point.proceed();
    }
    */

}
